<?php
// 应用公共文件
use think\Db;

function get_goods_bytp($type,$page,$storeid,$goodstp=0){
	
	if($type == 4){
		return getInformation($page,$storeid,$goodstp=0);
	}
	if($type == 5 || $type == 6){
		$storeid = 1;
	}
	
	$pagesize = config('PageSize');
	$startpage = $page*$pagesize;
	
	$where = ['type'=>$type,'storeid'=>$storeid,'isshow'=>1];
	if($goodstp>0){
		$where = ['storeid'=>$storeid,'type'=>$type,'isshow'=>1,'goodstp'=>$goodstp];
	}
	
	
    $goods = Db::name('goods')->where($where)
    ->field('id,gname,message,price,type,icon,showType,buyType,buynum,topicon,discount,addtime')
    ->limit($startpage,$pagesize)
	->order('id desc')
    ->select();
	
	return $goods;
}

//获得资讯
function getInformation($page,$storeid,$goodstp=0){
	$pagesize = config('PageSize');
	$startpage = $page*$pagesize;
	
	$where = ['storeid'=>$storeid,'isshow'=>1];
	if($goodstp>0){
		$where = ['storeid'=>$storeid,'isshow'=>1,'goodstp'=>$goodstp];
	}
	
	
    $goods = Db::name('information')->where($where)
    ->field('id,gname,message,type,icon,addtime')
    ->limit($startpage,$pagesize)
	->order('goodstp desc,id desc')
    ->select();
	
	return $goods;
}

function get_goodstp($storeid){
	$goodstp = Db::query("select * from ml_goods_type where storeid = $storeid");
	return $goodstp;
}

//获取用户信息
function get_user_info($uid){
	$uinfo = Db::query("select u.userid,u.role,u.accounts,u.source,u.storeid,p.username,p.phone,p.headimgurl,p.sex,p.fullname,p.birthday from ml_userinfo u,ml_userinfo_p p
	where u.unionid = p.unionid and u.userid = $uid");
	
	if(count($uinfo)<=0){
		return [];
	}
	
	return $uinfo[0];
}


//获取店铺信息
function get_store_info($storeid){
	$storeinfo = Db::name('store')->where(['store_id'=>$storeid])->find();
	return $storeinfo;
}

function vget($url){

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); 
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $output = curl_exec($ch);
    curl_close($ch);
    return json_decode($output, true);

}


/**
 * 发送短信逻辑
 * @param unknown $scene
 */
function sendSms($scene, $sender, $params,$unique_id=0)
{
    $smsLogic = new \app\common\logic\SmsLogic;
    return $smsLogic->sendSms($scene, $sender, $params, $unique_id);
}


/**
 * 检查手机号码格式
 * @param $mobile 手机号码
 */
function check_mobile($mobile){
    if(preg_match('/1[34578]\d{9}$/',$mobile))
        return true;
    return false;
}


/**
 * 获取随机字符串
 * @param int $randLength  长度
 * @param int $addtime  是否加入当前时间戳
 * @param int $includenumber   是否包含数字
 * @return string
 */
function get_rand_str($randLength=6,$addtime=1,$includenumber=0){
    if ($includenumber){
        $chars='abcdefghijklmnopqrstuvwxyzABCDEFGHJKLMNPQEST123456789';
    }else {
        $chars='abcdefghijklmnopqrstuvwxyz';
    }
    $len=strlen($chars);
    $randStr='';
    for ($i=0;$i<$randLength;$i++){
        $randStr.=$chars[rand(0,$len-1)];
    }
    $tokenvalue=$randStr;
    if ($addtime){
        $tokenvalue=$randStr.time();
    }
    return $tokenvalue;
}

//登录更新方法
function loginUpdate($userinfo,$storeid,$unionid,$wxopenid=''){
	//查看这个openid + storeid 是否存在。
	//如果存在更新一下头像
	//如果不存在添加到数据库	
	
	$openid = $userinfo['openid'];
	$headimgurl = $userinfo['headimgurl'];
	$nickname = $userinfo['nickname'];
		
	$ruser = Db::query("select userid from ml_userinfo where unionid='$unionid' and storeid=$storeid"); //Db::name('userinfo')->where(['openid'=>$openid,'storeid'=>$storeid])->field('userid')->select();
	$userid = 0;
	if(count($ruser)>0){
		$userid = $ruser[0]['userid'];
		//Db::name('userinfo')->where(['userid'=>$userid])->save(['headimgurl'=>$headimgurl,'wxopenid'=>$wxopenid]);
		if($wxopenid!=''){
			Db::name('userinfo')->where(['userid'=>$userid])->save(['wxopenid'=>$wxopenid]);
		}
	}
	else{
		$adddata = [];

		$adddata['role'] = 1;
		$adddata['openid'] = $openid;
		$adddata['wxopenid'] = $wxopenid;
		$adddata['unionid'] = $unionid;
		$adddata['regTime'] = time();
		$adddata['storeid'] = $storeid;
		$regTime = time();
		Db::query("insert into ml_userinfo(role,openid,regTime,storeid,unionid,wxopenid) values (1,'$openid',$regTime,$storeid,'$unionid','$wxopenid') ");
		//Db::name('userinfo')->insert($adddata);
		$userid = Db::name('userinfo')->getLastInsID();
	}
	
	addUserInfo_p($unionid,$userinfo,$wxopenid);
	addLoginHistory($unionid,$storeid);
	return ['uid'=>$userid,'nickName'=>$nickname];
}

//用户公共信息
function addUserInfo_p($unionid,$userinfo){
	
	$headimgurl = $userinfo['headimgurl'];
	$nickname = $userinfo['nickname'];
	$nums = Db::name('userinfo_p')->where(['unionid'=>$unionid])->count();
	if($nums<=0){
		$p_data = [];
		$p_data['username']=$nickname;
		$p_data['unionid']=$unionid;
		$p_data['headimgurl']=$headimgurl;
		
		if(isset($userinfo['sex'])){
			$p_data['sex'] = $userinfo['sex'];
		}
		else{
			$p_data['sex'] = $userinfo['gender'];
		}		
		Db::name('userinfo_p')->insert($p_data);
	}
	else{
		Db::name('userinfo_p')->where(['unionid'=>$unionid])->save(['headimgurl'=>$headimgurl]);
	}
}

//登录店铺历史
function addLoginHistory($unionid,$storeid){	
	if($storeid==17){
		return;
	}
	$loginNum = Db::name("userlogin")->where(['unionid'=>$unionid])->count();
	//只保留6次记录数据
	if($loginNum>6){
		$deleteNum = $loginNum-6;
		Db::query("delete from ml_userlogin where unionid = '$unionid' order by id asc limit $deleteNum");
	}
	
	Db::name("userlogin")->insert(['unionid'=>$unionid,'storeid'=>$storeid,'times'=>time()]);	
}

//登录检查订单中是否有超时的券
function loginCheckOrder($userid){
	$resBuy = Db::name('buylist')->where(['userid'=>$userid,'orderstate'=>1])->select();
	
	$couponlist = [];
	$curtime = time();
	foreach($resBuy as $key=>$value){
		$couponlist = Db::name('consumelist')->where(['buyid'=>$value['buyid']])->select();
		$cnum = count($couponlist);
		
		foreach($couponlist as $k=>$v){
			
			if($v['states']>0){
				$cnum-=1;
			}
			else if($curtime > $v['dateto']){
				Db::name('consumelist')->where(['consumeid'=>$v['consumeid']])->save(['states'=>2]);
				$cnum-=1;
			}
		}
		
		if($cnum<=0){
			Db::name('buylist')->where(['buyid'=>$value['buyid']])->save(['orderstate'=>2]);
		}		
	}
}

//按照类型获得广告
function getAdByType($a_type,$storeid){	
	//加载所有可以显示的首页广告
	$adinfo = Db::query("select ml_ad.*,id,gname,ml_goods.type,message,price from ml_ad,ml_goods where ml_ad.goodsid = ml_goods.id 
	and ml_ad.storeid = $storeid and ml_ad.isshow = 1 and ml_ad.atype=$a_type");
	return $adinfo;
}

function update_pay_status($order_sn,$data){
	$data['buydate'] = time();
	db('buylist')->where(['order_sn'=>$order_sn])->save($data);
	
	$buyres = db('buylist')->where(['order_sn'=>$order_sn])->select();
	if(count($buyres)<=0){
		return false;
	}
	
	$goodsid = $buyres[0]['goodsid'];
	$ginfo = Db::name('goods')->where(['id'=>$goodsid])->find();	
	if(empty($ginfo)){
		return false;
	}
	$gtype = $ginfo['type'];
	if($gtype == 5){
		return update_import_payback($buyres);
	}
	else{
		return update_payback($buyres);
	}
	return false;
}

//购买修改返回{$buyres}
function update_payback($buyres){
	$goodsid = $buyres[0]['goodsid'];
	$num = $buyres[0]['buyNum'];
	$accounts = $buyres[0]['price']*0.01;
	$lastbuyid = $buyres[0]['buyid'];
	$userid = $buyres[0]['userid'];
	$buyid = $buyres[0]['buyid'];
	$setsname = $buyres[0]['setsname'];
	Db::query("update ml_goods set buynum = buynum+$num where id=$goodsid");
	$couponList = db('coupontogoods')->where(['goodsid'=>$goodsid])->select();
			
	for($j = 0;$j<$num;$j++){

		//给玩家添加礼品券			
		if(count($couponList)>0){
			
			$arrlen = count($couponList);
			$couponMsg;
			
			for($i = 0;$i<$arrlen;$i++){
				
				$cid = $couponList[$i]['couponid'];
				$couponMsg = db('coupon')->where(['id'=>$cid])->select();//$DB->query("select * from xl_coupon where id = ".$cid);
				
				if(count($couponMsg)<=0){
					continue;
				}
				
				$datefrom = time() + $couponMsg[0]['starttime'];
				$dateto = $datefrom + $couponMsg[0]['endtime'];
				
				$adddata = ['coupon'=>$cid,
				'userid'=>$userid,
				'datefrom'=>$datefrom,
				'dateto'=>$dateto,
				'goodsid'=>$goodsid,
				'buyid'=>$lastbuyid,
				'states'=>0];
				
				db('consumelist')->add($adddata);					
			}					
		}
	}
	
	
	//绑定关系
	$Boss = config('Boss');
	$User = config('User');	
	$userinfo = Db::name('userinfo')->where(['userid'=>$userid])->field('userid,storeid,unionid')->select();
	$storeid = $userinfo[0]['storeid'];
	$unionid = $userinfo[0]['unionid'];
	
	$userinfo_p = Db::name('userinfo_p')->where(['unionid'=>$unionid])->select();
	
	wlog('...storeid'.$storeid);
	
	$bossinfo = Db::query("select userid from ml_userinfo where role = $Boss and storeid = $storeid order by userid asc");
	if(count($bossinfo)<=0){
		return true;
	}
	
	
	$BossUserid = $bossinfo[0]['userid'];	
	$client = Db::query("select * from ml_clientslist where belongto = ? and clientid = ?",array($BossUserid,$userid));
	
	if(count($client)<=0 && $BossUserid != $userid){
		//说明没有确定关系
		Db::query("insert into ml_clientslist(clientid,belongto,conndate,agentid)values(?,?,?,?)",array($userid,$BossUserid,time(),0));
	}		
	
	$price = $buyres[0]['price']*0.01;
	$bossMoney = floatval($price);//floatval($goodsRes[0]['commissionboss'] * $price);
	//老板娘收益
	Db::query("update ml_userinfo set accounts = accounts + ? where userid = ?",array($bossMoney,$BossUserid));	
	
	//用户消费记录		
	Db::query("insert into ml_userconsume(usetype,userid,touserid,nums,opdate,userrole,goodsname,storeid)values(?,?,?,?,?,?,?,?)",
	array(1,$userid,$BossUserid,$bossMoney,time(),$User,$setsname,$storeid));	
	
	//老板娘收支记录
	Db::query("insert into ml_userconsume(usetype,userid,touserid,nums,opdate,userrole,goodsname,storeid,clientname)values(?,?,?,?,?,?,?,?,?)",
	array(2,$BossUserid,$userid,$bossMoney,time(),$Boss,$setsname,$storeid,$userinfo_p[0]['username']));	
	
	return true;
}

//项目引进购买返回
function update_import_payback($buyres){
	$goodsid = $buyres[0]['goodsid'];
	$num = $buyres[0]['buyNum'];
	$accounts = $buyres[0]['price']*0.01;
	$lastbuyid = $buyres[0]['buyid'];
	$userid = $buyres[0]['userid'];
	$buyid = $buyres[0]['buyid'];
	$storeid = $buyres[0]['storeid'];
	$setsname = $buyres[0]['setsname'];
	Db::query("update ml_goods set buynum = buynum+$num where id=$goodsid");
	
	//给对应的店家添加一个项目引进 添加一条资讯。还有项目引进及资讯的绑定信息
	$User = config('User');
	$Boss = config('Boss');
	
	$goodRes = Db::name('goods')->where(['id'=>$goodsid])->find();
	$connRes = Db::name('import_info')->where(['importid'=>$goodsid])->find();
	
//	exit(json_encode($goodRes));
	
	if(empty($goodRes) || empty($connRes)){
		exit('out');
		return false;
	}
	$inforid = $connRes['infoid'];
	$infoRes = Db::name('Information')->where(['id'=>$inforid])->find();
	
	//添加一条项目引进
	//unset($goodRes['id']);
	$addRes = [];
	foreach($goodRes as $k=>$v){
		if($k == 'id')
			continue;
		$addRes[$k] = $goodRes[$k];
	}
	//exit();
	//exit(json_encode($addRes,false));
	$addRes['storeid'] = $storeid;
	$addRes['addtime'] = time();
	$addgid = Db::name('goods')->add($addRes);
	
	//添加资讯信息
	$addInfo = [];
	foreach($infoRes as $k=>$v){
		if($k == 'id')
			continue;
		$addInfo[$k] = $infoRes[$k];
	}
	$addInfo['storeid'] = $storeid;
	$addInfo['addtime'] = time();
	$addInfo['isshow'] = 0;
	$infoid = Db::name('Information')->add($addInfo);
	
	//添加关信息
	Db::name("import_info")->add(['importid'=>$addgid,'infoid'=>$infoid]);
	
	$bossinfo = Db::query("select userid from ml_userinfo where role = $Boss and storeid = $storeid order by userid asc");
	if(count($bossinfo)<=0){
		return true;
	}
	
	$BossUserid = $bossinfo[0]['userid'];	
	$client = Db::query("select * from ml_clientslist where belongto = ? and clientid = ?",array($BossUserid,$userid));
	
	if(count($client)<=0 && $BossUserid != $userid){
		//说明没有确定关系
		Db::query("insert into ml_clientslist(clientid,belongto,conndate,agentid)values(?,?,?,?)",array($userid,$BossUserid,time(),0));
	}		
	
	$price = $buyres[0]['price']*0.01;
	$bossMoney = floatval($price);//floatval($goodsRes[0]['commissionboss'] * $price);
	//老板娘收益
	Db::query("update ml_userinfo set accounts = accounts + ? where userid = ?",array($bossMoney,$BossUserid));	
	
	//用户消费记录		
	Db::query("insert into ml_userconsume(usetype,userid,touserid,nums,opdate,userrole,goodsname,storeid)values(?,?,?,?,?,?,?,?)",
	array(1,$userid,$BossUserid,$bossMoney,time(),$User,$setsname,$storeid));	
	
	//老板娘收支记录
	Db::query("insert into ml_userconsume(usetype,userid,touserid,nums,opdate,userrole,goodsname,storeid,clientname)values(?,?,?,?,?,?,?,?,?)",
	array(2,$BossUserid,$userid,$bossMoney,time(),$Boss,$setsname,$storeid,$userinfo_p[0]['username']));	
	
	return true;
}

function WxH5Login(){
	$storeid = input('storeid');
	$rooturl = config('ROOTURL');
	$appid = config('WxAppId');
	//$tourl = input('tourl/s','');
	$snsapitp = "snsapi_userinfo";
	
	//echo '$tourl='.urldecode('http%3A%2F%2Fwww.jubenxiong.com%2Fgames%2Fdianwu%2Fdetails%2F160');
	//exit();
	//echo '$tourl='.urldecode($tourl);
	//exit(urldecode($tourl));
	$redirect_uri = urlencode ($rooturl.'php/index.php/store/User/getuserinfo?storeid='.$storeid);
	
	//exit();
	
	$url ="https://open.weixin.qq.com/connect/oauth2/authorize?appid=$appid&redirect_uri=$redirect_uri&response_type=code&scope=$snsapitp&state=1#wechat_redirect";
	header("Location:".$url);
	//echo"<script>window.location.replace('".$url."');</script>";
	exit();
}

//主要是为了做查询in操作 把一个需要查询的结果集拼接成字符串处理
function ConnResultStr($result,$pars){
	$haveArr = [];
	foreach($result as $k=>$v){
		array_push($haveArr,$v[$pars]);
	}
	$haveStr = implode(',', $haveArr);
	$haveStr = "(".$haveStr.")";
	return $haveStr;
}

//给用户添加商品
function AddGoodsToUser($goodsid,$userid,$storeid){
	$goodRes = Db::name("goods")->where(['id'=>$goodsid])->field('id,gname,price')->find();
	if(empty($goodRes)){
		return ['state'=>-1,'msg'=>'商品信息错误'];
	}
	
	$order = [];
	$order['order_sn'] = get_rand_str(10,0,1);
	$order['price'] = $goodRes['price']*100;
	$order['goodsid'] = $goodsid;
	$order['userid'] = $userid;
	$order['setsname'] = $goodRes['gname'];
	$order['buydate'] = time();
	$order['orderstate'] = 0;
	$order['buyNum'] = 1;
	$order['paystate'] = 1;
	$order['storeid'] = $storeid;
	
	$lastbuyid = Db::name('buylist')->add($order);
	
	$couponList = db('coupontogoods')->where(['goodsid'=>$goodsid])->select();
			
	//给玩家添加礼品券			
	if(count($couponList)>0){
		
		$arrlen = count($couponList);
		$couponMsg;
		
		for($i = 0;$i<$arrlen;$i++){
			
			$cid = $couponList[$i]['couponid'];
			$couponMsg = db('coupon')->where(['id'=>$cid])->select();//$DB->query("select * from xl_coupon where id = ".$cid);
			
			if(count($couponMsg)<=0){
				continue;
			}
			
			$datefrom = time() + $couponMsg[0]['starttime'];
			$dateto = $datefrom + $couponMsg[0]['endtime'];
			
			$adddata = ['coupon'=>$cid,
			'userid'=>$userid,
			'datefrom'=>$datefrom,
			'dateto'=>$dateto,
			'goodsid'=>$goodsid,
			'buyid'=>$lastbuyid,
			'states'=>0];
			
			db('consumelist')->add($adddata);					
		}					
	}
	return ['state'=>'ok','msg'=>'添加成功'];
}

//是否绑定手机
function isBindPhone($userid){
	$res = Db::name("userinfo")->where(['userid'=>$userid])->find();
	if(empty($res)){
		return '';
	}
	
	$ures = Db::name("userinfo_p")->where(['unionid'=>$res['unionid']])->find();
	if(empty($ures)){
		return '';
	}	
	return $ures['phone'];
}

function wlog($txt){
	$txt = $txt.'\n';
	$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
	fwrite($myfile, $txt);
	fclose($myfile);
}
	